/*
 * @Author: 秦福凯
 * @LastEditTime: 2025-10-31 15:17:49
 * @Description: 网络请求封装
 */
import axios from 'axios'
import {baseapi} from './baseapi'
import { ElMessageBox,ElMessage } from 'element-plus';




export function backGoLogin(msg){
  ElMessageBox.confirm(msg,'系统提示',
    {
    confirmButtonText: '确认',
    showCancelButton: false,
    type: 'warning',
    }
  ).then(() =>{
    localStorage.clear();
    sessionStorage.clear();
    location.replace('/');
  })
}

//创建一个xios实例
const service = axios.create({
  // 超时设置
  timeout: 1000000
})
// 请求拦截
service.interceptors.request.use(
 config =>{
   config.headers.token = localStorage.getItem('token')
   return config
 },
 err =>{
   return Promise.reject();
 }
)
// 响应拦截
service.interceptors.response.use(
  response => {
    // removePending(response.config);
    let data = response.data
    if(data.code == 701){
      backGoLogin('凭证失效,请重新登录')
    }
    else{
      return response;
    }
  },
  error =>{
    if(error.response.status == 500){
      ElMessage.warning('服务器异常!')
    }
    return Promise.reject(error.response)   // 返回接口返回的错误信息
  }
)

// 自定义网络请求，get post
export function getMethod(method:string,url:string,parmas:any):Promise<void> {
  service.defaults.headers.post['Content-Type'] = 'application/json'
  return service({
    method:method,
    url,
    data:parmas,
  })
}

/// 附件上传 请求头 content-type为 form-data的post请求
export function upload(url:any,data:any,){
  service.defaults.headers.post['Content-Type'] = 'multipart/form-data'
  return service.post(url,data)
}

// 下载方法
export function dowload(method:string,url:string,parmas:any):Promise<void>{
  return new Promise((resolve,reject) =>{
    service({
      method,
      url,
      data:parmas,
      responseType:'arraybuffer',
    }).then(res =>{
      console.log(res.headers)
      let fileType = ''
      let fileName = ''
      if(res.headers['content-disposition']){
        fileType = res.headers['content-disposition'].split(';')[1].split('.')[1]
        console.log(res.headers['content-disposition'].split(';')[1].split('.')[0].split('filename=')[1])
        // 解码 以及截取类型
        fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('.')[0].split('filename=')[1])
      }
      // 使用bolb 加 a标签进行下载
      let blob = new Blob([res.data])// 具体数据参照后端接口返回的数据结构
      let objectUrl = URL.createObjectURL(blob);
      var downloadElement = document.createElement('a');
      downloadElement.href = objectUrl;
      downloadElement.download = fileName +'.' + fileType 
      downloadElement.click(); //点击下载
      resolve(res)
    }).catch((err) =>{
      reject(err)
    })
  })
}
